package org.zb.object;

import org.newdawn.slick.GameContainer;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.geom.Vector2f;
import org.newdawn.slick.util.Log;
import org.zb.common.VectorUtil;
import org.zb.controller.GameController;

public class MovingObject extends PhysicalObject {

	public Vector2f target = new Vector2f();
	public Vector2f movement = new Vector2f();
	public Vector2f lastMovement = new Vector2f();
	
	// temporary vector (optimization)
	public Vector2f positionAfterMovement = new Vector2f();
	
	public float speed = 0.1f;

	protected boolean hasMoved = true;
	
	public double calculateTheta() {
		return movement.getTheta();
	}
	
	public Vector2f calculateMovement() {
		movement.set(target);
		movement.sub(position).normalise().scale(speed);
		
		
		double newTheta = movement.getTheta();
		double lastTheta = lastMovement.getTheta();
		
		double thetaDif = lastTheta - newTheta;
		double step = speed * 10;
		
		if(Math.abs(thetaDif) < step || Math.abs(thetaDif) > 360 - step)
			return movement;
		
		if(thetaDif > 180)
			thetaDif = thetaDif - 360;
		else if(thetaDif < -180)
			thetaDif = thetaDif + 360;
		
		step = thetaDif > 0 ? step : -step;
		
		movement.setTheta(lastTheta - step);
		
		return movement;
	}
	
	public final Vector2f calculatePositionAfterMovement() {
		positionAfterMovement.set(position);
		return positionAfterMovement.add(movement);
	}
	
	@Override
	public void update(GameContainer container, int delta) throws SlickException {
		movement = calculateMovement().scale(delta / 10);
		
		for(int i=0;i<4;i++)
			if(!GameController.movement.canMove(this))
				movement.scale(0.5f);
		
		hasMoved = false;
		
		if(target.distance(position) < speed) {
			// nothing so far
		} else if(GameController.movement.canMove(this)) {
			position.add(movement);
			lastMovement.set(movement);
			hasMoved = true;
		} else {
			lastMovement.setTheta(movement.getTheta());
			hasMoved = false;
		}
	}
	
	@Override
	public String toString() {
		return super.toString() + ", target: " +  target;
	}
	
}
